import OnSaleAPI from '@/api/OnSale';
import {
  Box,
  FieldCols,
  FormSection,
  mapField,
  useCall,
  useFieldCtx,
  useFormValue,
  useQueryValue,
  useReq,
  useSimpleMemo,
} from '@/components';
import { companyFields } from '@/constants/sharedFields';
import { SelectPackage } from '@/pages/components';
import OnsaleInfoProvider from '@/pages/sales/components/OnsaleInfoProvider';
import ShowProductList from '@/pages/sales/components/ShowProductList';
import { joinComma, pathJoin, simpleMerge } from '@/utils';
import { CITE_TREE } from '@/utils/cities';
import { catchAndScrollFor } from '@/utils/fp';
import { Button, DatePicker, Form, Input, message, Space, Spin, TreeSelect } from 'antd';
import moment from 'moment';
import React, { useEffect, useMemo, useRef } from 'react';
import EditAttachments from './components/EditAttachments';
import EditQuest from './components/EditQuest';
import PackageContext from './components/PackageContext';
import useOrgData from './components/useOrgData';

function PackageConfigInput({ value, onChange, ...props }) {
  const form = useFieldCtx('form');
  const companyCode = useFormValue(form, 'companyCode');
  const selectedKeys = useSimpleMemo(value ? [value] : []);
  const handleOk = useCall(([selected]) => {
    if (!selected) return false;
    onChange?.(selected.packageCode);
    form.setFieldsValue({ onSaleName: selected.packageName });
  });

  const onService = useCall((formData) => [{ ...formData, t: { ...formData.t, companyCode } }]);

  return (
    <>
      <SelectPackage selectedKeys={selectedKeys} onService={onService} onOk={handleOk}>
        <Input {...props} value={value} readOnly />
      </SelectPackage>
    </>
  );
}

function ComboRange(props) {
  const form = useFieldCtx('form');
  let { value, onChange, ...rest } = props;
  let endValue = useFormValue(form, 'onSaleEndTime');
  const state = useMemo(() => {
    return [value != null ? moment(value) : null, endValue != null ? moment(endValue) : null];
  }, [value, endValue]);

  const handleChange = (newValue) => {
    let [start, end] = newValue || [];
    if (start != null) start = start.startOf('day').format('YYYY-MM-DD HH:mm:ss');
    if (end != null) end = end.endOf('day').format('YYYY-MM-DD HH:mm:ss');
    form.setFieldsValue({ onSaleBeginTime: start, onSaleEndTime: end });
  };

  return <DatePicker.RangePicker {...rest} value={state} onChange={handleChange} />;
}

const orgData = (props) => ({
  ...props,
  getValueProps(v) {
    return { value: v?.split(',').filter(Boolean) || [] };
  },
  getValueFromEvent(values) {
    return values?.map((v) => v.value || v).join(',');
  },
  getFieldProps() {
    return {
      multiple: true,
      treeCheckable: true,
      treeCheckStrictly: false,
      maxTagCount: 3,
      treeNodeFilterProp: 'label',
      treeData: useOrgData() || [],
      showCheckedStrategy: TreeSelect.SHOW_PARENT,
    };
  },
});

const citesData = (props) =>
  joinComma({
    ...props,
    treeData: CITE_TREE,
    treeCheckable: true,
    allowClear: true,
    placeholder: '请输入电投地区',
    treeCheckStrictly: false,
    maxTagCount: 3,
    showCheckedStrategy: TreeSelect.SHOW_PARENT,
  });

function AddPage({ history, location }) {
  const onsaleId = useQueryValue('onsaleId');
  const xhr = useReq(OnSaleAPI.getById);
  const saveXhr = useReq(OnSaleAPI.insertOrUpdate);
  const [form] = Form.useForm();
  const packageCode = useFormValue(form, ['packageCode']);
  const edit1 = useRef();
  const edit2 = useRef();

  //
  const isElect = useFormValue(form, 'isElectricPin', (v) => v === '1');
  useEffect(() => {
    if (!isElect) {
      form.setFieldsValue({
        saleChannel: null,
        linkUrl: null,
      });
    }
  }, [isElect]);

  const fields = [
    ...companyFields,
    ['packageCode', '组合编码', PackageConfigInput, { required: true }],
    ['onSaleName', '名称', null, { required: true }],
    ['saleBussessType', '业务分类', 'dict', { required: true, code: 'agency', hides: [''] }],
    ['onsaleType', '人群分类', 'dict', { code: 'population_type', initialValue: '' }],
    ['insurePlace', '计划书投保地区', 'tree', orgData({ required: true })],
    [
      'isElectricPin',
      '在线投保',
      'radio-group',
      {
        initialValue: '0',
        options: [
          { value: '0', label: '不支持' },
          { value: '1', label: '支持' },
        ],
      },
    ],
    [
      'saleChannel',
      '销售渠道',
      'select',
      {
        colProps: { hidden: !isElect },
        initialValue: null,
        options: [
          { value: null, label: '无' },
          { value: 'D1', label: '在线投保' },
          { value: 'H5', label: '投保链接' },
        ],
      },
    ],
    [
      'linkUrl',
      '投保链接',
      null,
      { colProps: { required: true, hidden: useFormValue(form, 'saleChannel', (v) => v !== 'H5') } },
    ],
    ['electricPinPlace', '电投地区', 'tree', citesData({ required: true, colProps: { hidden: !isElect } })],
    ['onSaleBeginTime', '销售日期', ComboRange, { required: true }],
    ['onSaleEndTime', '销售日期', 'hidden', { noStyle: true, colProps: { xs: 0, md: 0, xl: 0 } }],
    ['imgUrl', '封面图', 'upload', { required: true }],
  ].map(mapField);

  useEffect(() => {
    if (onsaleId) xhr.start(onsaleId);
  }, [onsaleId]);
  const $data = xhr.result?.data || null;
  useEffect(() => {
    if ($data) form.setFieldsValue($data);
  }, [$data]);

  const handleSave = useCall(async () => {
    // 保存问卷
    await edit1.current?.onSave();

    // 保存在售信息
    const values = await form.validateFields().catch(catchAndScrollFor(form));
    const data = simpleMerge(
      { isRecommend: '0', shelves: '1' },
      values.isElectricPin === '1' ? { onSaleStatus: '1' } : null,
      xhr.result?.data ?? null,
      values,
    );
    await saveXhr.start(data);
    // END 保存在售信息

    // 保存附件
    await edit2.current?.onSave();

    message.success('保存成功');
    history.replace(pathJoin(location.pathname, '../'));
  });

  const loading = [xhr.status, saveXhr.status].includes('loading');

  return (
    <>
      <Spin spinning={loading}>
        <Form component={false} form={form}>
          <FormSection title='产品上下架配置'>
            <FieldCols form={form} fields={fields} />
          </FormSection>
        </Form>

        {!!packageCode && (
          <PackageContext packageCode={packageCode}>
            {isElect && <EditQuest ref={edit1} />}
            <EditAttachments ref={edit2} />
          </PackageContext>
        )}

        {!!onsaleId && !!packageCode && (
          <OnsaleInfoProvider packageCode={packageCode}>
            <ShowProductList />
          </OnsaleInfoProvider>
        )}

        <Box flex jus='center' py={3} className='form-page-btn'>
          <Space size='large'>
            <Button onClick={history.goBack}>返回</Button>
            <Button type='primary' onClick={handleSave}>
              保存
            </Button>
          </Space>
        </Box>
      </Spin>
    </>
  );
}

export default AddPage;
